package com.easytake.emotioncat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easytake.emotioncat.entity.EmUserInfoEntity;
import com.easytake.emotioncat.mapper.EmUserInfoMapper;
import com.easytake.emotioncat.service.IEmUserInfoService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2022-10-23
 */
@Service
public class EmUserInfoServiceImpl extends ServiceImpl<EmUserInfoMapper, EmUserInfoEntity> implements IEmUserInfoService {
    @Resource
    EmUserInfoMapper userInfoMapper;

    public Boolean removeByUserId(String userId) {
        EmUserInfoEntity dbUser = queryByUserId(String.valueOf(userId));
        if (Objects.isNull(dbUser)) {
            throw new IllegalArgumentException("用户不存在");
        }
        super.removeById(dbUser.getId());
        //todo 补充删除宠物记录和日志记录信息
        return false;
    }


    @Override
    public EmUserInfoEntity queryByUserId(String userId) {
        QueryWrapper<EmUserInfoEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EmUserInfoEntity::getUserId, userId);
        List<EmUserInfoEntity> userInfoEntityList = this.list(queryWrapper);
        if (userInfoEntityList.size() > 0) {
            return userInfoEntityList.get(0);
        }
        return null;
    }

    public EmUserInfoEntity queryByPhone(String phone) {
        QueryWrapper<EmUserInfoEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EmUserInfoEntity::getPhone, phone);
        List<EmUserInfoEntity> userInfoEntityList = this.list(queryWrapper);
        if (userInfoEntityList.size() > 0) {
            return userInfoEntityList.get(0);
        }
        return null;
    }

    // 如果用户不存在，则新增用户
    @Async
    public void addUserIfNewVisitAsync(String openid) {
        EmUserInfoEntity entity = queryByUserId(openid);
        if (Objects.nonNull(entity)) {
            return;
        }
        entity = new EmUserInfoEntity();
        entity.setUserId(openid);
        LocalDateTime now = LocalDateTime.now();
        entity.setCreateTime(now);
        entity.setModifyTime(now);
        save(entity);
    }
}
